import sys, os
from Ui_main import *
from PyQt4 import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.Qwt5.qplt import *
from Numeric import *
from numpy import *
from scipy import *
from pylab import *
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from numpy.fft import fft, rfft, fftshift, fftfreq
import def_algo as algor
import datetime
import ser
import popen2


class Magnet(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_mainWin()
        self.ui.setupUi(self)
        
        self.pocetVz = 1000
        
        self.connect(self.ui.btnK1, QtCore.SIGNAL("clicked()"),  self.OtvorSuborK1)
        self.connect(self.ui.btnK2, QtCore.SIGNAL("clicked()"),  self.OtvorSuborK2)
        self.connect(self.ui.btnK3, QtCore.SIGNAL("clicked()"),  self.OtvorSuborK3)
        self.connect(self.ui.btnK4, QtCore.SIGNAL("clicked()"),  self.OtvorSuborK4)
        
        self.connect(self.ui.btnStartMer, QtCore.SIGNAL("clicked()"), self.Zaznam)
        
        self.connect(self.ui.pushButton,  QtCore.SIGNAL("clicked()"), self.Kresli)
        
        self.connect(self.ui.tabMag, QtCore.SIGNAL("clicked()"), self.vyber)
        
        self.connect(self.ui.comboVzorky, QtCore.SIGNAL("activated(QString)"), self.vzorky)
        
        #self.connect(self.ui.btnStartMer, QtCore.SIGNAL("clicked()"), self.Volba)
        
        self.ui.tabMag.setColumnCount(4)
        
        self.ui.tabMag.setHorizontalHeaderItem(0, QTableWidgetItem('K1'))
        self.ui.tabMag.setHorizontalHeaderItem(1, QTableWidgetItem('K2'))
        self.ui.tabMag.setHorizontalHeaderItem(2, QTableWidgetItem('K3'))
        self.ui.tabMag.setHorizontalHeaderItem(3, QTableWidgetItem('K4'))
        
        self.connect(self.ui.btn_vyberAdres, QtCore.SIGNAL("clicked()"), self.Uloz)
        
        self.ui.barPrepocet.setMaximum(self.pocetVz)
        
        self.stateK1 = False
        self.stateK2 = False
        self.stateK3 = False
        self.stateK4 = False
        
        #print self.pocetVz
        
        self.k1=[]
        self.k2=[]
        self.k3=[]
        self.k4=[]
        
        #self.canvas = FigureCanvasQTAgg(self.ui.plotWidget)
        self.TempAdres = '/home'
        self.axes = self.ui.plotWidget
        self.UlozAdres = self.TempAdres
        
        self.grid = QwtPlotGrid()
        self.grid.enableXMin(True)
        self.grid.setMajPen(QPen(Qt.white, 0, Qt.DotLine))
        self.grid.setMinPen(QPen(Qt.gray, 0 , Qt.DotLine))
        
        self.ui.qPlot.setCanvasBackground(Qt.darkGreen)
        self.ui.qPlot_2.setCanvasBackground(Qt.darkGreen)
        self.ui.qPlot_3.setCanvasBackground(Qt.darkGreen)
        self.ui.qPlot_4.setCanvasBackground(Qt.darkGreen)
        
        
    def Volba(self):
        self.stateK1=self.ui.uloz_k1.isChecked()
        self.stateK2=self.ui.uloz_k2.isChecked()
        self.stateK3=self.ui.uloz_k3.isChecked()
        self.stateK4=self.ui.uloz_k4.isChecked()
        #print (self.stateK1,  self.stateK2)
        
    def vzorky(self, qstring):
        self.pocetVz = int(qstring)
        
    
    #print vzorky
    
    def OtvorSuborK1(self):
        self.k1 = self.OtvorSubor(0)
        self.Tabulka(0, self.k1)
        self.PlotGraph(0, self.k1)
      
    def OtvorSuborK2(self):
        self.k2 = self.OtvorSubor(1)
        self.Tabulka(1, self.k2)
        self.PlotGraph(1, self.k2)
        
    def OtvorSuborK3(self):
        self.k3 = self.OtvorSubor(2)
        self.Tabulka(2, self.k3)
        self.PlotGraph(2, self.k3)
    
    def OtvorSuborK4(self):
        self.k4 = self.OtvorSubor(3)
        self.Tabulka(3, self.k4)
        self.PlotGraph(3, self.k4)

    def Uloz(self):
        self.UlozAdres = QFileDialog.getExistingDirectory(self, "Vyber adresar")
        self.ui.lineAdres.setText(self.UlozAdres)
    
    def Zaznam(self):
        #/home/gandhi/Dropbox/
        self.ui.tabMag.clear()
        self.Volba()
        t = datetime.datetime.now()
        self.k1, self.k2, self.k3, self.k4, synab, citac = ser.CitMag("/home/gandhi/Dropbox/Magnetometer/1/cat_pato_28-12-2008", self.pocetVz, True).Dekodovanie()
        #self.k1, self.k2, self.k3, self.k4, synab, citac = ser.CitMag("/dev/ttyUSB0", self.pocetVz, False).Dekodovanie()
        self.Tabulka(0, self.k1)
        self.PlotGraph(0, self.k1)
        
        self.Tabulka(1, self.k2)
        self.PlotGraph(1, self.k2)
        
        self.Tabulka(2, self.k3)
        self.PlotGraph(2, self.k3)
        
        self.Tabulka(3, self.k4)
        self.PlotGraph(3, self.k4)
        
        if self.stateK1 == True:
            suborK1 = str(self.UlozAdres) +"/" + t.strftime("%d%m%Y_%H%M%S") + "_K1.txt"
            f_k1 = open(suborK1, 'w')
            savetxt(f_k1, self.k1)
            f_k1.close()
        if self.stateK2 == True:
            suborK2 = str(self.UlozAdres) +"/" + t.strftime("%d%m%Y_%H%M%S") + "_K2.txt"
            f_k2 = open(suborK2, 'w')
            savetxt(f_k2, self.k2)
            f_k2.close()
        if self.stateK3 == True:
            suborK3 = str(self.UlozAdres) +"/" + t.strftime("%d%m%Y_%H%M%S") + "_K3.txt"
            f_k3 = open(suborK3, 'w')
            savetxt(f_k3, self.k3)
            f_k3.close()
        if self.stateK4 == True:
            suborK4 = str(self.UlozAdres) +"/" + t.strftime("%d%m%Y_%H%M%S") + "_K4.txt"
            f_k4 = open(suborK4, 'w')
            savetxt(f_k4, self.k4)
            f_k4.close()
  
     
    def OtvorSubor(self,  k):
        if k == 0:
            line = self.ui.lineK1
        elif k == 1:
            line = self.ui.lineK2
        elif k == 2:
            line = self.ui.lineK3
        elif k == 3:
            line = self.ui.lineK4
            
        subor = QtGui.QFileDialog.getOpenFileName(self, 'Choose a file to open', self.TempAdres, 'Text Files *.txt')
        if subor:
            self.TempAdres = os.path.dirname(str(subor))
            line.setText(subor)
            f = open(subor, 'r')
            k = loadtxt(f)
            f.close()
            return k
        
    def Tabulka(self, col, k):
        row = 0
        for line in k:
            if self.ui.tabMag.rowCount() < row:
                self.ui.tabMag.insertRow(row)
            elif self.ui.tabMag.rowCount() == row:
                self.ui.tabMag.insertRow(row)
            self.ui.tabMag.setItem(row, col, QTableWidgetItem(str(line)))
            row = row + 1
           
    def PlotGraph(self,  k,  data):
        if k == 0:
            graph = self.ui.qPlot
            graph_fft = self.ui.qPlot_fft
            graph.clear()
            graph_fft.clear()
            popis = "K1"
        elif k == 1:
            graph = self.ui.qPlot_2
            graph_fft = self.ui.qPlot_fft_2
            graph.clear()
            graph_fft.clear()
            popis = "K2"
        elif k == 2:
            graph = self.ui.qPlot_3
            graph_fft = self.ui.qPlot_fft_3 
            graph.clear()
            graph_fft.clear()
            popis = "K3"
        elif k == 3:
            graph = self.ui.qPlot_4
            graph_fft = self.ui.qPlot_fft_4
            graph.clear()
            graph_fft.clear()
            popis = "K4"
        
            
        self.grid.attach(graph)
        
        self.curve = QwtPlotCurve(popis)
        self.curve2 = QwtPlotCurve("FFT")
                
        ff = fft(data)
        
        self.curve.setPen(QPen(Qt.red))
        self.curve2.setPen(QPen(Qt.blue))
        r = arange(0,  len(data), 1)
        r2 = arange(0,  len(ff), 1)
            
        self.curve.setData(r, data)
        self.curve2.setData(r2, abs(ff[1:len(ff)]))
           
        graph.insertLegend(Qwt.QwtLegend(), Qwt.QwtPlot.BottomLegend)
        
        self.curve.attach(graph)
        self.curve2.attach(graph_fft)
        
        graph.replot()   
        graph_fft.replot() 
        
    def Kresli(self):
        B = algor.Algo(10, 10, self.k1, self.k2, self.k3, self.k4)
        dat = B.Vypocet()
        for i in range(0, 10):
            obr = resize(dat[:,i], (10, 10))
            im = imshow(obr,  interpolation='bicubic', animated=True)
            im.set_data(obr)
        show()
    
    def vyber(self):
        list = self.ui.tabMag.selectedItems()
        print list
        print 'ok'
